package com.hboxs.asl.controller.asl.product;

import com.hboxs.asl.Filter;
import com.hboxs.asl.JsonMessage;
import com.hboxs.asl.Page;
import com.hboxs.asl.Pageable;
import com.hboxs.asl.controller.asl.BaseController;
import com.hboxs.asl.entity.*;
import com.hboxs.asl.entity.Product.OrderType;
import com.hboxs.asl.service.*;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.*;

/**
 * Controller - 产品
 */
@Controller("aslProductionController")
@RequestMapping("/weChat/product")
public class ProductControl extends BaseController {

    protected Logger logger = Logger.getLogger(getClass().getName());

    @Resource(name = "productServiceImpl")
    private ProductService productService;
    @Resource(name = "productCategoryServiceImpl")
    private ProductCategoryService productCategoryService;
    @Resource(name = "searchServiceImpl")
    private SearchService searchService;
    @Resource(name = "cartServiceImpl")
    private CartService cartService;
    @Resource(name = "memberServiceImpl")
    private MemberService memberService;
    @Resource(name = "adPositionServiceImpl")
    private AdPositionService adPositionService;
    @Resource(name = "adServiceImpl")
    private AdService adService;
    @Resource(name = "viewHistoryServiceImpl")
    private ViewHistoryService viewHistoryService;
    @Resource(name = "reviewServiceImpl")
    private ReviewService reviewService;
    @Resource(name = "cartItemServiceImpl")
    private CartItemService cartItemService;

    /**
     * 商品首页
     *
     * @param pcId
     * @param orderType
     * @param pageable
     * @param model
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Long pcId, Product.OrderType orderType, Pageable pageable, ModelMap model) {
        Member member = memberService.getCurrent();
        long totalPages;
        ProductCategory pc = productCategoryService.find(pcId);
        pageable.setPageNumber(1);
        pageable.setPageSize(10);
        Page<Product> page = productService.findPageGroup(
                pc, null, null, null, null, null, null, true, null, null, null, null, orderType, pageable
        );
        if(member!=null){
            model.addAttribute("count", cartService.getTotalNumberOfGoodsInCart(member.getCart()));
        }
        model.addAttribute("totalPages", page.getTotalPages());
        model.addAttribute("page", page);
        model.addAttribute("productCategory", pc);
        model.addAttribute("orderType", orderType);
        return "/yijing/product-list";
    }


    /**
     * 商品列表
     *
     * @param pcId
     * @param orderType
     * @param pageable
     * @return
     */
    @RequestMapping(value = "/page", method = RequestMethod.GET)
    public
    @ResponseBody
    Object page(Long pcId, Product.OrderType orderType,
                Pageable pageable) {
        ProductCategory pc = productCategoryService.find(pcId);
        pageable.setPageSize(10);
        Page page = productService.findPageGroup(
                pc, null, null, null, null, null, null, true, null, null, null, null, orderType, pageable
        );

        List<Product> products = page.getContent();

//        for (Product p : products){
//            System.out.println(p.getId());
//        }
        HashMap<Long, Integer> reviewCount = new HashMap<>();
        for (Product product : products) {
            reviewCount.put(product.getId(), product.getReviews().size());
        }
        HashMap<Long, Integer> orderItemCount = new HashMap<>();
        for (Product product : products) {
            orderItemCount.put(product.getId(), product.getOrderItems().size());
        }

        return JsonMessage.success(

                "totalPage", page.getTotal(),

                "pageNumber", pageable.getPageNumber(),

                "content", JsonMessage.optimiseObj(
                        products,
                        "id", "image", "name", "reviews", "price", "promotionPrice", "finalScore", "weight"
                ),
                "reviewCount", reviewCount,
                "orderItemCount", orderItemCount

        );

    }

    /**
     * 列表
     */
    @RequestMapping(value = "/l", method = RequestMethod.GET)
    public String list(Long pc, OrderType order, Integer pageNumber, ModelMap model, HttpSession session) {
        try {
            // 商品分类
            ProductCategory session_productCategory = (ProductCategory) session.getAttribute("productCategory");
            Set<ProductCategory> productCategories = null;
            if (session_productCategory != null) {
                productCategories = session_productCategory.getChildren();
            }
            model.addAttribute("session_productCategory", session_productCategory);
            model.addAttribute("productCategories", productCategories);

            // 选中的商品分类
            ProductCategory productCategory = productCategoryService.find(pc);
            if (productCategory == null) {
                Iterator<ProductCategory> it = productCategories.iterator();
                if (it.hasNext()) {
                    productCategory = it.next();
                }
            }
            model.addAttribute("productCategory", productCategory);

            // 默认每页20个
            if (pageNumber == null) {
                pageNumber = 1;
            }
            // 默认每页20个
            Pageable pageable = new Pageable(pageNumber, null);

            model.addAttribute("pageNumber", pageNumber);
            model.addAttribute("page",
                    productService.findPage(productCategory, null, null, null, null, null, null, true, null, null, null, null, order, pageable));


            List<Filter> banner_position_fs = new ArrayList<Filter>();
            banner_position_fs.add(Filter.eq("name", "公告"));
            // banner位置
            AdPosition banner_position = adPositionService.findList(1, banner_position_fs, null).get(0);
            List<Filter> banner_fs = new ArrayList<Filter>();
            banner_fs.add(Filter.eq("adPosition", banner_position));
            List<Ad> banners = adService.findList(null, banner_fs, null);
            if (banners != null && banners.size() > 0) {
                model.addAttribute("ad", banners.get(0));
            } else {
                model.addAttribute("ad", null);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/yijing/html/goods-list";
    }

    @RequestMapping(value = "/evFresh", method = RequestMethod.GET)
    public String evFresh(ModelMap modelMap, Pageable pageable) {
        Member member = memberService.getCurrent();
        List<Ad> ads = adService.findListByAdPosition("每日新鲜广告");
        pageable.getFilters().add(Filter.eq("evFresh", Boolean.TRUE));

        modelMap.addAttribute("count", cartService.getTotalNumberOfGoodsInCart(member.getCart()));
        modelMap.addAttribute("evFresh", productService.findEvFresh());
        modelMap.addAttribute("ads", ads);
        return "/yijing/product-list-new";
    }

    /**
     * 产品详情
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public String detail(Long id, ModelMap model) {
        try {
            Product product = productService.find(id);
            if (product == null) {
                return "/yijing/404";
            }
            product.setHits(product.getHits() + 1);
            productService.update(product);
            Member member = memberService.getCurrent();
            viewHistoryService.create(member, product);

            if(member!=null){
                model.addAttribute("count", cartService.getTotalNumberOfGoodsInCart(member.getCart()));
                model.addAttribute("isFavorite", productService.isFavorite(product, member));
            }

            model.addAttribute("product", product);
            model.addAttribute("reviews", reviewService.lastThreeReviews(product));

            // 商品属性
            Map<String, String> attributeValue = new HashMap<String, String>();
            Set<Attribute> attributes = product.getProductCategory().getAttributes();
            for (Attribute attribute : attributes) {
                String value = product.getAttributeValue(attribute);
                if (value != null) {
                    value = value.replaceAll(",", " ");
                    attributeValue.put(attribute.getName(), value);
                }
            }
            model.addAttribute("attributeValue", attributeValue);

            return "/yijing/product-detail";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/yijing/404";
    }

    /**
     * 产品详情
     *
     * @param id
     * @param model
     * @param anchorId 主播id
     * @return
     */
    @RequestMapping(value = "/changeSpec", method = RequestMethod.GET)
    public String changeSpec(Long id, ModelMap model, Long anchorId) {
        try {
            Product product = productService.find(id);

            product.setHits(product.getHits() + 1);
            productService.update(product);
            Member member = memberService.getCurrent();
            viewHistoryService.create(member, product);
            BigDecimal dealPrice = product.getPromotionPrice() != null ? product.getPromotionPrice() : product.getPrice();
            model.addAttribute("optional", true);
            model.addAttribute("product", product);
            model.addAttribute("count", cartService.getTotalNumberOfGoodsInCart(member.getCart()));
            model.addAttribute("reviews", reviewService.lastThreeReviews(product));
            model.addAttribute("isFavorite", productService.isFavorite(product, member));

            int quantity = 1;

            Cart cart = cartService.getCurrent(memberService.getCurrent());
            if (Cart.MAX_PRODUCT_COUNT != null && cart.getCartItems().size() >= Cart.MAX_PRODUCT_COUNT) {
                return "/yijing/product-detail";
            }

            if (cart.contains(product)) {
                CartItem cartItem = cart.getCartItem(product);
                if (CartItem.MAX_QUANTITY != null && cartItem.getQuantity() + quantity > CartItem.MAX_QUANTITY) {
                    return "/yijing/product-detail";
                }
                if (product.getStock() != null && cartItem.getQuantity() + quantity > product.getAvailableStock()) {
                    return "/yijing/product-detail";
                }
                cartItemService.add(cartItem, quantity);
            } else {
                if (CartItem.MAX_QUANTITY != null && quantity > CartItem.MAX_QUANTITY) {
                    return "/yijing/product-detail";
                }
                if (product.getStock() != null && quantity > product.getAvailableStock()) {
                    return "/yijing/product-detail";
                }
                cartItemService.create(product, quantity, cart, null, anchorId);
            }

            return "/yijing/product-detail";
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "/yijing/404";
    }

    /**
     * 产品图文详情
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "/introduction", method = RequestMethod.GET)
    public String introduce(Long id, ModelMap model) {
        try {
            Product product = productService.find(id);
            if (product == null) {
                return "/yijing/404";
            }
            // 商品属性
            Map<String, String> attributeValue = new HashMap<String, String>();
            Set<Attribute> attributes = product.getProductCategory().getAttributes();
            for (Attribute attribute : attributes) {
                String value = product.getAttributeValue(attribute);
                if (value != null) {
                    value = value.replaceAll(",", " ");
                    attributeValue.put(attribute.getName(), value);
                }
            }
            model.addAttribute("attributeValue", attributeValue);
            model.addAttribute("product", product);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/yijing/product-detail2";
    }


    /**
     * 索引搜索页面
     *
     * @return
     */
    @RequestMapping(value = "/search_index", method = RequestMethod.GET)
    public String searchIndex() {
        try {
            return "/yijing/search";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/404.html";
    }

    /**
     * 搜索首页
     *
     * @param k
     * @param pageable
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.GET)
    public String search(String k, Pageable pageable, ModelMap modelMap) {
        try {
            pageable.getFilters().add(Filter.like("name", "%" + k + "%"));
            Page<Product> productPage = productService.findPageGroup(null, null, null, null, null, null, null, true, null, null, null, null, null, pageable);
            modelMap.addAttribute("productPage", productPage);
            modelMap.addAttribute("totalPages", productPage.getTotalPages());
            modelMap.addAttribute("pageNumber", productPage.getPageNumber());
            return "/yijing/search-details";
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return "/404.html";
    }

    /**
     * 搜索页面更新
     *
     * @param name
     * @param pageable
     * @return
     */
    @RequestMapping(value = "/searchPage", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage search(String name, Pageable pageable) {
        try {
            pageable.getFilters().add(Filter.like("name", "%" + name + "%"));
            Page<Product> productPage = productService.findPageGroup(null, null, null, null, null, null, null, true, null, null, null, null, null, pageable);
            return JsonMessage.success(productPage);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 搜索快捷提示
     *
     * @param keyword
     * @param response
     */
    @RequestMapping(value = "/sugg", method = RequestMethod.GET)
    public void suggestSearch(String keyword, HttpServletResponse response) {
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            if (null == keyword || StringUtils.isEmpty(keyword.trim())) {
                pw.print("");
                return;
            }
            String[] keywordArray = searchService.suggestSearch(keyword);
            StringBuffer keys = new StringBuffer();
            for (int i = 0; i < keywordArray.length; i++) {
                if (i == keywordArray.length - 1) {
                    keys = keys.append(keywordArray[i]);
                }
                keys.append(keywordArray[i] + ",");
            }
            pw.print(keys);
            return;
        } catch (Exception e) {
            logger.error("搜索快捷提示错误" + e);
        } finally {
            pw.close();
        }
    }

    /**
     * 点击数
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/hits/{id}", method = RequestMethod.GET)
    public
    @ResponseBody
    Long hits(@PathVariable Long id) {
        return productService.viewHits(id);
    }
}
